//
//  OADetailDisPatchController.m
//  maocuhuiOASystem
//
//  Created by michael on 16/3/22.
//  Copyright © 2016年 czd. All rights reserved.
//

#import "OADetailDisPatchController.h"
#import "OADetailDisPatchCell.h"
#import "GDataDefines.h"
#import <QuickLook/QuickLook.h>
#import "OAHistroyViewController.h"
#import "OAAttachmentsModel.h"
#import "OASelectDepartmentController.h"
#import "OADepartmentModel.h"
#import "ComingworkongController.h"
#import "PickerChoiceView.h"

@interface OADetailDisPatchController ()<UIWebViewDelegate,QLPreviewControllerDataSource,QLPreviewControllerDelegate,UITextViewDelegate,TFPickerDelegate>
{
    NSInteger selectIndex;
}
@property(nonatomic,strong)OADetailDispatchModel * detailPatchModel ;
@property(nonatomic,strong)NSMutableArray * attachmentArray; //附件
@property(nonatomic,strong)NSMutableArray * mainattachmentArray; //正文附件
@property(nonatomic,strong)NSString * attacmentURL;
@property(nonatomic,strong)NSMutableArray * contentsData;

@property(nonatomic,assign)BOOL isEditoring; //编辑中
@property(nonatomic,strong)NSMutableArray * departments;

@property(nonatomic,copy)NSString * infoString; //服务器返回字段 根据该字段跳转不同的界面
@property(nonatomic,copy)NSString * textString ; //记录填写的意见
@property(nonatomic,copy)NSString * body;
@property(nonatomic,strong)NSMutableArray * subItems;  //选中 需要提交得数据


@end

@implementation OADetailDisPatchController
-(NSMutableArray*)contentsData{
    if (_contentsData == nil) {
        _contentsData = [NSMutableArray array];
    }
    return _contentsData;
}

-(NSMutableArray*)attachmentArray{
    if (_attachmentArray ==nil) {
        _attachmentArray = [NSMutableArray array];
    }
    return _attachmentArray;
}

-(NSMutableArray*)subItems{
    if (_subItems ==nil) {
        _subItems = [NSMutableArray array];
    }
    return _subItems;

}
-(NSMutableArray*)mainattachmentArray{
    if (_mainattachmentArray == nil) {
        _mainattachmentArray = [NSMutableArray array];
    }
    return _mainattachmentArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
     self.title = @"详情";
    self.tableView.estimatedRowHeight = 0;
self.tableView.estimatedSectionHeaderHeight = 0;
self.tableView.estimatedSectionFooterHeight = 0;
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc]initWithTitle:@"流转历史" style:UIBarButtonItemStylePlain target:self action:@selector(historyAction)];
    self.navigationItem.rightBarButtonItem = rightItem;
    self.tableView.hidden = YES;
 //加载网络数据
    [self loadData];
    [self requestData];
    if (self.isAlreadDoneWork) {//已办工作不需要编辑
   // self.footView.backgroundColor = [UIColor redColor];
    self.footView.hidden = YES;
   // self.footView.height = 0;
    self.tableView.contentSize = CGSizeMake(KScreenWidth, KScreenHeight);
       
}
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, _tableView.bottom, KScreenHeight, 44)];
//    view.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:view];
    if (self.isUnDoWork) {
        [self.operationBtn setTitle:@"签收" forState:UIControlStateNormal];
    }else{
        [self.operationBtn setTitle:@"编辑" forState:UIControlStateNormal];

   }
   UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(keybordDown)];
//    [self.view addGestureRecognizer:tap];
}
- (void)keybordDown {
//[self.TextField resignFirstResponder];
//    [self.TextField1 resignFirstResponder];
//    [self.TextField2 resignFirstResponder];
    
    [self.view endEditing:YES];
        }
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
//    [UIView animateWithDuration:0.2 animations:^{
//    self.view.transform = CGAffineTransformMakeTranslation(0, -200);
//    }];
//  
//    return YES;
UIView *view = textView.superview;

while (![view isKindOfClass:[UITableViewCell class]]) {

view = [view superview];

}

UITableViewCell *cell = (UITableViewCell*)view;

CGRect rect = [cell convertRect:cell.frame toView:self.view];
if(textView == self.workField){
self.tableView2.contentInset = UIEdgeInsetsMake(0, 0, KScreenHeight/2, 0);
[self.tableView2 scrollToRowAtIndexPath:[self.tableView indexPathForCell:cell] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}
if (rect.origin.y / 2 + rect.size.height>=KScreenHeight/2) {

self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 216, 0);
//self.tableView2.contentInset = UIEdgeInsetsMake(0, 0, 216, 0);
//[self.tableView2 scrollToRowAtIndexPath:[self.tableView indexPathForCell:cell] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];

[self.tableView scrollToRowAtIndexPath:[self.tableView indexPathForCell:cell] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];


}
return YES;

}
- (void)textViewDidEndEditing:(UITextView *)textView{
    
    [UIView animateWithDuration:0.2 animations:^{
         self.view.transform = CGAffineTransformIdentity;
    }];
   
    
}
#pragma mark 流转历史
-(void)historyAction{
    OAHistroyViewController* historyVC = (OAHistroyViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"HistoryVC"];
    historyVC.fileId = self.fileId;
    [self.navigationController pushViewController:historyVC animated:YES];
}

- (IBAction)operationAction:(id)sender {
 UIButton * btn = (UIButton*)sender;
    if (self.isUnDoWork && [btn.currentTitle isEqualToString:@"签收"]) {//从待办工作路径过来 先调用 签收 接口
        [self setupSign]; //签收
    }else{
        if ([btn.currentTitle isEqualToString:@"编辑"]) {
        if ([_tianxie isEqualToString:@"no"]) {
     [btn setTitle:@"取消" forState:UIControlStateNormal];
     [self.saveButton setTitle:@"" forState:UIControlStateNormal];
            self.isEditoring = YES;
            self.saveButton.enabled = NO;
            self.sendButton.enabled = YES;

}else{
        
        //开始编辑
            [btn setTitle:@"取消" forState:UIControlStateNormal];
            self.isEditoring = YES;
            self.saveButton.enabled = YES;
            self.sendButton.enabled = YES;

            
            }
            
            
            
        }else{
            [btn setTitle:@"编辑" forState:UIControlStateNormal]; //取消编辑
            self.isEditoring = NO;
            self.saveButton.enabled = NO;
            self.sendButton.enabled = NO;
            [_tableView2 removeFromSuperview];
        }
    }
    [self.tableView reloadData];

}

#pragma mark 签收
-(void)setupSign{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"unId":self.fileId},@{@"userId":userId}];
    [HttpTools postWithURL:KexchdataURL arrays:array method:KSetSignInMethod success:^(id JSON) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [self.operationBtn setTitle:@"编辑" forState:UIControlStateNormal];
        [self.view makeToast:@"签收成功"];
        [self operationAction:self.operationBtn];
         [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOADetailData" object:nil];
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];
    
    
}
#pragma mark 加载网络数据
-(void)loadData{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"unId":self.fileId},@{@"userId":userId}];
    [HttpTools postWithURL:KexchdataURL arrays:array method:KGetOAOfficeMethod success:^(id JSON) {
    NSLog(@"=====%@",JSON);
    if (!JSON) {
    self.footView.hidden = YES;
}
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        self.tableView.hidden = NO;
        self.detailPatchModel = [self getDetailModel:JSON];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];
    
}
- (void)requestData{

[MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId}];
    [HttpTools postWithURL:KexchgeneralURL arrays:array method:@"dailyPage" success:^(id JSON) {
    NSLog(@"=====%@",JSON);
    NSData * data = [JSON dataUsingEncoding:NSUTF8StringEncoding];
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（Users）
    GDataXMLElement *rootElement = [doc rootElement];
    NSMutableArray *array = [NSMutableArray array];
    //获取根节点下的节点（User）
    NSArray *rootData= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement *subData in rootData) {
        NSArray * tempArray = [subData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in tempArray) {
            GDataXMLElement *documentElement= [[data elementsForName:@"日常用语"] objectAtIndex:0];
            NSString *str= [documentElement stringValue];
            
            [array addObject:str];
            
           
            
        }
        _array = array;
    }
    
    
    
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
       
                } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];




}
//获取解析得到的数据。
-(OADetailDispatchModel *)getDetailModel:(NSString*)dataString;
{
    NSData * data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    OADetailDispatchModel * detailModel = [[OADetailDispatchModel alloc]init];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（Users）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（User）
    NSArray *rootData= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement *subData in rootData) {
        NSArray * tempArray = [subData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in tempArray) {
            GDataXMLElement *documentElement= [[data elementsForName:@"文档"] objectAtIndex:0];
            detailModel.document = [documentElement stringValue];
            
             GDataXMLElement *titleElement= [[data elementsForName:@"文档1"] objectAtIndex:0];
            
//            detailModel.title = [titleElement stringValue];

            NSArray *array = [[titleElement stringValue] componentsSeparatedByString:@"##"]; //从字符A中分隔成2个元素的数组
_string = array[1];
          [_tableView reloadData];
            
           GDataXMLElement *filestep= [[data elementsForName:@"填写意见环节"] objectAtIndex:0];
            detailModel.flow = [filestep stringValue];
             if ([detailModel.flow isEqualToString:@""]) {
    self.tianxie = @"no";
}

            GDataXMLElement *fileId= [[data elementsForName:@"唯一标识"] objectAtIndex:0];
            detailModel.fileId = [fileId stringValue];
            
        }
    }
    
    for (GDataXMLElement * subData in rootData) {
        NSArray * tempArray = [subData elementsForName:@"数据实体"];
        for (GDataXMLElement * element in tempArray) {
            NSArray *array = [element elementsForName:@"附件"];
            for (GDataXMLElement * data in array) {
                OAAttachmentsModel * attachModel = [[OAAttachmentsModel alloc]init];
                GDataXMLElement * nameElement = [[data elementsForName:@"名称"] objectAtIndex:0];
                NSString *  name = [nameElement stringValue];
                attachModel.attachmentsTitle = name;
                
                GDataXMLElement * contentElement = [[data elementsForName:@"内容"] objectAtIndex:0];
                NSString *  content = [contentElement stringValue];
                attachModel.attachmentsURL = content;
                
                [self.attachmentArray addObject:attachModel];
            }
        }
    }
    
    for (GDataXMLElement * subData in rootData) {
        NSArray * tempArray = [subData elementsForName:@"正文实体"];
        for (GDataXMLElement * element in tempArray) {
            NSArray *array = [element elementsForName:@"附件"];
            for (GDataXMLElement * data in array) {
                OAAttachmentsModel * attachModel = [[OAAttachmentsModel alloc]init];
                GDataXMLElement * nameElement = [[data elementsForName:@"名称"] objectAtIndex:0];
                NSString *  name = [nameElement stringValue];
                attachModel.attachmentsTitle = name;
                
                GDataXMLElement * contentElement = [[data elementsForName:@"内容"] objectAtIndex:0];
                NSString *  content = [contentElement stringValue];
                attachModel.attachmentsURL = content;
                
                [self.mainattachmentArray addObject:attachModel];
            }
        }
    }
    
    return detailModel;
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
if (tableView == _tableView2) {
    return 1;
}

else{
    return 4;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == _tableView) {
    switch (section) {
     case 0:
     return 1;
     case 3:
            return self.detailPatchModel.formArray.count;
            break;
        case 1:
            return self.mainattachmentArray.count;
        case 2:
            return self.attachmentArray.count;
        default:
            return 1;
            break;

    }

}else{
return _array.count+2;


}
    


}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{




if (tableView ==_tableView) {
    
if (indexPath.section == 0) {
      CGFloat titleSize = [OAToolBox sizebyText:_string font:14 minsWidth:80];

 UITableViewCell* cell = [[UITableViewCell alloc]init];
      UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 50, titleSize)];
    label.text = @"标题 :";
     label.numberOfLines = 0;
    label.font = [UIFont systemFontOfSize:14];
    [cell.contentView addSubview:label];
      UILabel  *label1 = [[UILabel alloc]init];
      label1.frame = CGRectMake(label.right,0, KScreenWidth-60,titleSize);
 [label1 setFont:[UIFont systemFontOfSize:14]];
 label1.numberOfLines = 0;
    label1.text = _string;
       [cell.contentView addSubview:label1];
             return cell;
    }
   else if (indexPath.section == 3) {
        OADetailDisPatchCell * cell = [OADetailDisPatchCell cellWihtTableView:tableView];
        cell.textView.delegate = self;
        NSString * allString = self.detailPatchModel.formArray[indexPath.row];
        cell.detailModel = self.detailPatchModel;
        cell.allString = allString;
         [cell editStatus:self.isEditoring];
        return cell;
    }

 else if (indexPath.section == 1) {
            static NSString * cellIdentifier = @"cellIdentifier";
            UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            }
            OAAttachmentsModel * model = self.mainattachmentArray[indexPath.row];
            cell.textLabel.text = model.attachmentsTitle;
            cell.textLabel.font = [UIFont systemFontOfSize:14];
            cell.textLabel.numberOfLines = 0;
            cell.textLabel.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
//            cell.backgroundColor = [UIColor redColor];
            return cell;
            
        } else{
            static NSString * cellIdentifier = @"cellId";
            UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            }
            OAAttachmentsModel * model = self.attachmentArray[indexPath.row];
            cell.textLabel.text = model.attachmentsTitle;
            cell.textLabel.font = [UIFont systemFontOfSize:14];
            cell.textLabel.numberOfLines = 0;
            cell.textLabel.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
//            cell.backgroundColor = [UIColor yellowColor];
            return cell;

        }
        }else{
        
    if (indexPath.row ==0) {
     UITableViewCell* cell = [[UITableViewCell alloc]init];
               cell.selectionStyle = UITableViewCellSelectionStyleNone;

      UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, cell.contentView.height)];
    label.text = @"填写意见 ";
    label.font = [UIFont systemFontOfSize:14];
    [cell.contentView addSubview:label];
      UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];
      but.frame = CGRectMake(kScreenWidth*.8-60, label.top+10,40,30);
     [but setTitle:@"确定" forState:UIControlStateNormal];
     [but addTarget:self action:@selector(action) forControlEvents:UIControlEventTouchUpInside];
     but.titleLabel.font    = [UIFont systemFontOfSize: 14];
 [but.layer setBorderColor:[UIColor blackColor].CGColor];
    [but.layer setBorderWidth:1];
    [but.layer setMasksToBounds:YES];

     [but setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
       [cell.contentView addSubview:but];
             return cell;

}
if (indexPath.row == 1) {

     UITableViewCell* cell = [[UITableViewCell alloc]init];
               cell.selectionStyle = UITableViewCellSelectionStyleNone;

      _workField = [[UITextView alloc]init];
      _workField.text = _textString;
      _workField.frame = CGRectMake(10, 10, KScreenWidth*.8-20, 80);
      UIColor *myColor = [UIColor colorWithWhite:0.5 alpha:0.2];
      _workField.backgroundColor = myColor;
 [_workField setFont:[UIFont systemFontOfSize:12]];
      _workField.delegate = self;
       [cell.contentView addSubview:_workField];
             return cell;

}else{
 static NSString * cellIdentifier = @"cellId";
            UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

//               cell.selectionStyle = UITableViewCellSelectionStyleNone;

            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            }
            if (cell.selected) {
    cell.accessoryType = UITableViewCellAccessoryCheckmark;

}           cell.textLabel.text = _array[indexPath.row-2];
            cell.textLabel.font = [UIFont systemFontOfSize:14];
            cell.textLabel.numberOfLines = 0;
            cell.textLabel.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
            return cell;

}
  }

    }
    


    

- (void)action{

if (_workField.text.length==0) {
 [self.view makeToast:[NSString stringWithFormat:@"请填写意见!"]];
{
//    _tableView2 = [[UITableView alloc]initWithFrame:CGRectMake(KScreenWidth*.1,  (KScreenHeight-64)*.1, KScreenWidth*.8, (KScreenHeight-64)*.8) style:UITableViewStylePlain];
//    
//    _tableView2.delegate = self;
//    _tableView2.dataSource = self;
//    self.tableView2.layer.borderWidth = 1;
//self.tableView2.layer.borderColor = [[UIColor blackColor] CGColor];    [_tableView2 reloadData];
//        [self.view addSubview:_tableView2];

}
}else{
[_tableView2 removeFromSuperview];

_textString =_workField.text;

[[NSNotificationCenter defaultCenter] postNotificationName:@"xxx" object:nil userInfo:@{@"string":_textString}];
[_tableView reloadData];


}
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

if (tableView ==_tableView) {
    if (indexPath.section == 0)
{
      CGFloat titleSize = [OAToolBox sizebyText:_string font:14 minsWidth:80];
        if (titleSize < 44) {
           return 44;
        }else{
return titleSize;
    }
    
    }
    if (indexPath.section == 3) {
        NSString * allString = self.detailPatchModel.formArray[indexPath.row];
        CGFloat height =  [allString boundingRectWithSize:CGSizeMake(KScreenWidth - 30, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} context:nil].size.height;
        if (height < 44) {
            height = 44;
        }
        return height + 10;
    }else{
        return 54;
    }

}else{
if(indexPath.row==1){
return 100;

}
else{

return 45;
}



}
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section==1) {
        UIView * bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 21)];
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, KScreenWidth, 21)];
        label.text = @"正文";
//        label.backgroundColor = [UIColor yellowColor];
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
        [bgView addSubview:label];
        if (self.mainattachmentArray.count!= 0) {
            label.hidden = NO;
        }else{
            label.hidden = YES;
        }
        return bgView;
    }
        if (section==2) {
        UIView * bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 21)];
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, KScreenWidth, 21)];
        label.text = @"附件";
//        label.backgroundColor = [UIColor grayColor];
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
        [bgView addSubview:label];
        if (self.attachmentArray.count!= 0) {
            label.hidden = NO;
        }else{
            label.hidden = YES;
        }
        return bgView;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==1) {
    if (_mainattachmentArray.count !=0) {
     return 21;
}else{

 return 0.001;


}
           }
    if (section==2) {
 if (_attachmentArray.count!=0) {
     return 21;

}else{

 return 0.001;


}
    }
    return 0.001;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

if (tableView ==_tableView){


    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1) { //下载附件 查看附件信息
        OAAttachmentsModel * model = self.mainattachmentArray[indexPath.row];
        [self openFileURL:model.attachmentsURL];
    }else if (indexPath.section == 2){
        OAAttachmentsModel * model = self.attachmentArray[indexPath.row];
        [self openFileURL:model.attachmentsURL];
    }
    }
    else{
    if (indexPath.row >1) {
       _workField.text = _array[indexPath.row-2];
    
}else{

nil;
}
    
    }
   
}
-(void)openFileURL:(NSString*)url{
    NSString * stringurl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    self.attacmentURL =  [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[url lastPathComponent]]; //附件路径
 
    if ([self isExtistFilePathWithFileName:[[NSURL URLWithString:stringurl] lastPathComponent]]) { //已经存在附件
        QLPreviewController *previewoCntroller = [[QLPreviewController alloc] init] ;
        previewoCntroller.delegate=self;
        previewoCntroller.dataSource=self;
        previewoCntroller.navigationItem.rightBarButtonItem=nil;
        [self.navigationController pushViewController: previewoCntroller animated:YES];
        
    }else{
        MBProgressHUD * hud  =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.labelText = @"下载中...";
        NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:stringurl]];
        [self.webView loadRequest:request];
    }
    
}

#pragma mark PreviewDataSource
//第一个方法是设定一组文档浏览的个数，会影响到在文档预览中的上/下一页。
-(NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller {
    return 1;
}
//第二个方法是指定文档预览的文件路径
-(id<QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index {
    
    return [NSURL fileURLWithPath:self.attacmentURL];
}

-(BOOL)isExtistFilePathWithFileName:(NSString*)fileName{
    NSString * file = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString * filePath = [file stringByAppendingPathComponent:fileName];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath] && fileName.length != 0) {
        return YES;
    }else{
        return NO;
    }
    
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSURL * requestedURL = [request URL];
    NSData * fileData = [[NSData alloc] initWithContentsOfURL:requestedURL];
    NSString * filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
     [fileData writeToFile:[filePath stringByAppendingPathComponent:[requestedURL lastPathComponent]] atomically:YES];
      return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
    
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    QLPreviewController *previewoCntroller = [[QLPreviewController alloc] init] ;
    previewoCntroller.delegate=self;
    previewoCntroller.dataSource=self;
    [self.navigationController pushViewController: previewoCntroller animated:YES];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}



- (IBAction)saveAction:(id)sender {


//PickerChoiceView *picker = [[PickerChoiceView alloc]initWithFrame:self.view.bounds];
////    selectIndex = indexPath.row;
//    picker.delegate = self;
//        
//        picker.selectLb.text = @"日常用语";
//        picker.customArr = _array;
//        
//
//    [self.view addSubview:picker];
if (_tableView2!= nil) {
    [_tableView2 removeFromSuperview];
            _tableView2 = nil;

}else{
    _tableView2 = [[UITableView alloc]initWithFrame:CGRectMake(KScreenWidth*.1,  (KScreenHeight-64)*.1, KScreenWidth*.8, (KScreenHeight-64)*.8) style:UITableViewStylePlain];
    
//    _tableView2.backgroundColor = [UIColor yellowColor];
    _tableView2.delegate = self;
    _tableView2.dataSource = self;
    self.tableView2.layer.borderWidth = 1;
self.tableView2.layer.borderColor = [[UIColor blackColor] CGColor];    [_tableView2 reloadData];
        [self.view addSubview:_tableView2];

}





//    if (self.textString.length ==0) {
//        self.textString = @"";
//    }
//
//    
//    [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
//    NSArray * array = nil;
//    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
//     if (self.detailPatchModel !=nil) {
//        self.body = [NSString stringWithFormat:@"&lt;?xml version=\'1.0\' encoding=\'utf-8\'?&gt;\n"
//                     "&lt;交换 xmlns=\'exch.jhsx.gov.cn/data\' xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\'&gt;\n"
//                     "&lt;数据&gt;\n"
//                     "&lt;数据元素&gt;\n"
//                     "&lt;%@&gt; %@ &lt;/%@&gt;\n"
//                     "&lt;/数据元素&gt;\n"
//                     "&lt;数据实体&gt;\n"
//                     "&lt;附件&gt;\n"
//                     "%@"
//                     "&lt;/附件&gt;\n"
//                     "&lt;/数据实体&gt;\n"
//                     "&lt;/数据&gt;\n"
//                     "&lt;/交换&gt;",
//                     self.detailPatchModel.flow,
//                     self.textString,
//                     self.detailPatchModel.flow,
//                     [self returnString]];
//        
//        array = @[@{@"unid":self.detailPatchModel.fileId},@{@"userId":userId},@{@"famxml":self.body}];
//    }
//
//    [HttpTools postWithURL:KexchdataURL arrays:array method:KSetSaveWork success:^(id JSON) {
//        [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
//        [self.view makeToast:@"保存成功"];
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOADetailData" object:nil];
//        
//    } failure:^(NSError *error) {
//        [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
//    }];
    
}
- (void)PickerSelectorIndixString:(NSString *)str{

//    NSDictionary *dict = [self.mutArray objectAtIndex:0];
//    
//    NSMutableDictionary *muDict = [NSMutableDictionary dictionaryWithDictionary:dict];
//    [muDict setObject:str forKey:@"title2"];
//    [self.mutArray replaceObjectAtIndex:0 withObject:muDict];
//    [self.mutArray removeObjectAtIndex:selectIndex];
//    [self.mutArray insertObject:muDict atIndex:selectIndex];
    
NSLog(@"%@",str);
self.textString = str;
  [self.tableView reloadData];
}

-(NSString *)returnString
{
    NSString *string = [[NSString alloc]init];
    string = @"&lt;名称&gt;%@&lt;/名称&gt;\n"
    "&lt;内容&gt;%@&lt;/内容&gt;\n";
    
    NSMutableString *str = [NSMutableString string];
    for (int i = 0; i<self.attachmentArray.count; i++) {
        OAAttachmentsModel * attachModel = self.attachmentArray[i];
        [str appendString: [NSString stringWithFormat:string,attachModel.attachmentsTitle,attachModel.attachmentsURL]];
    }
    
    return str;
}

- (IBAction)cilcuationAction:(id)sender {
    if (self.detailPatchModel.flow.length !=0) {
        if (self.textString.length == 0 && self.isEditoring) {
           {
    _tableView2 = [[UITableView alloc]initWithFrame:CGRectMake(KScreenWidth*.1,  (KScreenHeight-64)*.1, KScreenWidth*.8, (KScreenHeight-64)*.8) style:UITableViewStylePlain];
    
//    _tableView2.backgroundColor = [UIColor yellowColor];
    _tableView2.delegate = self;
    _tableView2.dataSource = self;
    self.tableView2.layer.borderWidth = 1;
self.tableView2.layer.borderColor = [[UIColor blackColor] CGColor];
   [_tableView2 reloadData];
        [self.view addSubview:_tableView2];

}
            return;
        }
    }

    [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    NSArray * array = nil;
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    if (self.detailPatchModel !=nil) {
        self.body = [NSString stringWithFormat:@"&lt;?xml version=\'1.0\' encoding=\'utf-8\'?&gt;\n"
                     "&lt;交换 xmlns=\'exch.jhsx.gov.cn/data\' xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\'&gt;\n"
                     "&lt;数据&gt;\n"
                     "&lt;数据元素&gt;\n"
                     "&lt;%@&gt; %@ &lt;/%@&gt;\n"
                     "&lt;/数据元素&gt;\n"
                     "&lt;数据实体&gt;\n"
                     "&lt;附件&gt;\n"
                     "%@"
                     "&lt;/附件&gt;\n"
                     "&lt;/数据实体&gt;\n"
                     "&lt;/数据&gt;\n"
                     "&lt;/交换&gt;",
                     self.detailPatchModel.flow,
                     self.textString,
                     self.detailPatchModel.flow,
                     [self returnString]];
        
        array = @[@{@"unid":self.detailPatchModel.fileId},@{@"userId":userId},@{@"famxml":self.body}];
        
    }
    
    
    [HttpTools postWithURL:KexchdataURL arrays:array method:KSetSubmitWorkMethod success:^(id JSON) {
        [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
        self.departments = [self dataWith:JSON];
        
        if ([self.infoString isEqualToString:@"11"]) { //成功发送，提交下一办理人
            
            
            [UIAlertView showWithTitle:@"提示" message:@"发送成功" cancelButtonTitle:@"确定" otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOADetailData" object:nil];
                [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];
            }];
            
        }else if ([self.infoString isEqualToString:@"12"]) { //返回环节信息
            OASelectDepartmentController * selectVC = [[OASelectDepartmentController alloc]init];
            selectVC.subItems = self.subItems;
            selectVC.body = self.body;
            selectVC.detailPatchModel = self.detailPatchModel;
            selectVC.attachmentArray = self.attachmentArray;
            selectVC.departments = self.departments;
            [self.navigationController pushViewController:selectVC animated:YES];
        }else if ([self.infoString isEqualToString:@"13"]) {//返回人员列表
            //            OASelectPersonController * selectPersonVC = [[OASelectPersonController alloc]init];
            //            selectPersonVC.personArray = self.personArray;
            //            selectPersonVC.body = self.body;
            //            selectPersonVC.setpString = self.setpString;
            //            if (self.detailModel ) {
            //                selectPersonVC.fileId = self.detailModel.fileId;
            //            }else if (self.detailPatchModel){
            //                selectPersonVC.fileId = self.detailPatchModel.fileId;
            //            }
            //
            //            [self.navigationController pushViewController:selectPersonVC animated:YES];
            
            
            
        }else if ([self.infoString isEqualToString:@"15"]){ //返回树
            //            OASelectPersonSecondController * selectPersonVC = [[OASelectPersonSecondController alloc]init];
            //            selectPersonVC.personArray = self.personArray;
            //            selectPersonVC.body = self.body;
            //            selectPersonVC.setpString = self.setpString;
            //            if (self.detailModel ) {
            //                selectPersonVC.fileId = self.detailModel.fileId;
            //            }else if (self.detailPatchModel){
            //                selectPersonVC.fileId = self.detailPatchModel.fileId;
            //            }
            //            selectPersonVC.groupArray = self.groupArray;
            //            selectPersonVC.rowArray = self.rowArray;
            //            [self.navigationController pushViewController:selectPersonVC animated:YES];
           
    
//    [self.view makeToast:@"归档成功"];
//    [self.navigationController popViewControllerAnimated:YES];
//     ComingworkongController *comvc =(ComingworkongController *) [self.storyboard instantiateViewControllerWithIdentifier:@"comvc"];
//    [self.navigationController pushViewController:comvc animated:YES];
    }
            
        
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
    }];
    
}
#pragma mark 数据解析

-(NSMutableArray*)dataWith:(NSString*)dataString
{
    NSData * data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableArray *arrData = [[NSMutableArray alloc]init];
    NSMutableArray * subData = [NSMutableArray array];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    GDataXMLElement *rootElement = [doc rootElement];
    NSArray *users = [rootElement children];
    for (int i = 0;i<[users count];i++) {
        GDataXMLElement *ele = [users objectAtIndex:i];
        if ([[ele name] isEqualToString:@"环节"]){
            OADepartmentModel * model = [[OADepartmentModel alloc]init];
            model.department = [[ele attributeForName:@"流向"] stringValue];
            for (int j=0; j<[ele childCount]; j++) {
                GDataXMLElement  *subItem = [ele childAtIndex:j];
                [subData addObject:subItem.stringValue];
            }
            [arrData addObject:model];
        }
    }
    self.subItems = subData; //选中 需要提交得数据
    NSArray *infoData= [rootElement elementsForName:@"info"];
    for (int i = 0;i<[infoData count];i++)
    {
        GDataXMLElement *infoElement = [infoData objectAtIndex:i];
        self.infoString = [infoElement stringValue];
    }
    
    return arrData;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    
    return YES;
    
}

- (void)textViewDidChange:(UITextView *)textView{
    self.textString = textView.text;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
